"""
实用函数
"""

import time
import os

def timeit(func):
    """
    计算函数运行时间的装饰器
    """
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        print("运行时间：", time.time() - start, "秒")
    return wrapper


def used_time(func):
    """
    计算语句运行时间
    """
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        return time.time() - start
    return wrapper


def time_format(seconds):
    """
    将秒数转换为格式化的时间字符串
    """
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    return "%02d:%02d:%02d" % (h, m, s)


def nohup(func):
    """
    使用 nohup 运行时，格式化输出记录的装饰器
    """
    def wrapper(*args, **kwargs):
        startTime = time.time()

        pid = os.getpid()
        print("[Nohup]"+ "-" * 50)
        print("[Nohup] Start @ %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(startTime)))
        print("[Nohup] PID: %d" % pid)

        func(*args, **kwargs)

        endTime = time.time()
        print("[Nohup] End @ %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(endTime)))
        print("[Nohup] Used Time: %s" % time_format(endTime - startTime))
        print("[Nohup]"+ "-" * 50 + "\n\n")

    return wrapper


if __name__ == "__main__":
    @nohup
    def test():
        time.sleep(1)
    test()